<template>
  <div>
    <span @click="searchFlagCheck" style="color: #409EFF; cursor: pointer;">
      展开搜索条件
    </span>
    <div v-if="searchFlag">
      <el-form :model="searchForm" label-width="120px">
        <el-form-item label="汽车ID">
          <el-input v-model="searchForm.carId" placeholder="请输入汽车ID"></el-input>
        </el-form-item>

        <el-form-item label="用户ID">
          <el-input v-model="searchForm.userId" placeholder="请输入商户ID"></el-input>
        </el-form-item>

        <el-form-item label="订单金额">
          <el-input v-model="searchForm.totalAmount" placeholder="请输入订单金额"></el-input>
        </el-form-item>

        <el-form-item label="支付方式">
          <el-input v-model="searchForm.paymentMethod" placeholder="请输入支付方式"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-if="userServiceEvaluate.list && userServiceEvaluate.list.length" :data="userServiceEvaluate.list" stripe>
      <el-table-column prop="orderId" label="订单号" />
      
      <el-table-column label="服务详情">
        <template #default="scope">
          <div>
            <el-button @click="scope.row.isExpanded = !scope.row.isExpanded">
              {{ scope.row.isExpanded ? '隐藏' : '显示' }} 详情
            </el-button>
            <div v-if="scope.row.isExpanded" style="margin-top: 10px;">
              <div v-if="scope.row.serviceDetail">
                <div v-if="parsedDetail = parseServiceDetail(scope.row.serviceDetail)">
                  服务编号: {{ parsedDetail.serviceId }} <br />
                  商家编号: {{ parsedDetail.shopId }} <br />
                  服务名: {{ parsedDetail.serviceName }} <br />
                  服务价格: {{ parsedDetail.servicePrice }} <br />
                  服务描述: {{ parsedDetail.details }} <br />
                  必需品: {{ parseServiceItems(parsedDetail.serviceItems) }} <br />
                  工时: {{ parsedDetail.estimatedTime }} <br />
                  服务条款: {{ parsedDetail.terms }} <br />
                  流程信息: {{ parseProcesses(parsedDetail.serviceProcesses) }} <br />
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="totalAmount" label="支付价格" />
      <el-table-column prop="appointmentTime" label="预约时间" />
      <el-table-column prop="payStatus" label="支付状态">
        <template v-slot="scope">
          {{ checkPay(scope.row.payStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="订单状态">
        <template v-slot="scope">
          {{ checkState(scope.row.orderState) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="findUserInfo(scope.row.userId)">联系买家</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-else>
      <p>没有待评价订单</p>
    </div>

    <el-dialog v-model="userFlag" title="用户联系方式">
      <div v-if="user">
        用户名：{{ user.userName }}<br />
        用户电话：{{ user.userPhone }}
      </div>
      <div v-else>
        <p>未查找到用户联系方式</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'OrderEvaluation',
  data() {
    return {
      searchFlag:false,
      userServiceEvaluate: { list: [] },
      searchForm: {
        carId: '',
        userId: '',
        totalAmount: '',
        paymentMethod: ''
      },
      user: {},
      userFlag: false,
    }
  },
  methods: {
    searchFlagCheck(){
      if(this.searchFlag){
        this.searchFlag = false;
      }else{
        this.searchFlag = true;
      }
    },
    findUserInfo(userId) {
      this.userFlag = true;
      this.$http.get("/user/userInfo/selectUserInfo", { params: { userId: userId } })
        .then(resp => {
          this.user = resp.data.data || {};
        })
        .catch(error => {
          console.error('获取用户信息失败:', error);
          this.user = {}; // 确保 user 在出错时是空对象
        });
    },
    checkPay(state) {
      const payStatus = ['未支付', '已支付', '支付中', '已退款', '退款中', '退款失败'];
      return payStatus[state] || '未知状态';
    },
    checkState(state) {
      const orderStates = ['已完成', '已取消', '已关闭', '进行中', '待评价', '待使用', '待发货'];
      return orderStates[state - 1] || '未知状态';
    },
    reset() {
      this.searchForm = {
        carId: '',
        userId: '',
        totalAmount: '',
        paymentMethod: ''
      };
      this.findServiceEvaluate();
    },
    search() {
      this.$http.get("/order/order/getOrderListShop", {
        params: {
          carId: this.searchForm.carId,
          userId: this.searchForm.userId,
          totalAmount: this.searchForm.totalAmount,
          paymentMethod: this.searchForm.paymentMethod,
          orderState: 5
        }
      }).then(resp => {
        this.userServiceEvaluate = resp.data.data || { list: [] };
        this.userServiceEvaluate.list.forEach(item => {
          item.isExpanded = false; // 初始化每个订单的展开状态
        });
      }).catch(error => {
        console.error('搜索订单失败:', error);
      });
    },
    parseServiceDetail(serviceDetail) {
      try {
        const detail = JSON.parse(serviceDetail);
        detail.serviceItems = detail.serviceItems ? JSON.parse(detail.serviceItems) : [];
        detail.serviceProcesses = detail.serviceProcesses ? JSON.parse(detail.serviceProcesses) : [];
        return detail;
      } catch (error) {
        console.error('解析 serviceDetail 时出错:', error);
        return {}; // 返回空对象以避免渲染错误
      }
    },
    parseServiceItems(serviceItems) {
      if (!serviceItems || serviceItems.length === 0) {
        return '无'; // 如果没有服务项目，显示“无”
      }
      return serviceItems.map(item => {
        return `服务编号: ${item.itemsId}, 数量: ${item.quantity}, 单价: ${item.unitPrice}`;
      }).join(', ');
    },
    parseProcesses(processes) {
      if (!processes || processes.length === 0) {
        return '无'; // 如果没有流程，显示“无”
      }
      return processes.map(item => {
        return `流程编号: ${item.processesId}, 工时: ${item.workingHours}, 单价: ${item.unitPrice}`;
      }).join(', ');
    },
    findServiceEvaluate() {
      this.$http.get("/order/order/getOrderListShop", { params: { orderState: 5 } })
        .then(res => {
          this.userServiceEvaluate = res.data.data || { list: [] };
          this.userServiceEvaluate.list.forEach(item => {
            item.isExpanded = false; // 初始化每个订单的展开状态
          });
        })
        .catch(error => {
          console.error('获取待评价订单失败:', error);
          this.userServiceEvaluate = { list: [] }; // 确保在出错时是空列表
        });
    }
  },
  created() {
    this.findServiceEvaluate();
  }
}
</script>

<style scoped>
/* 通用样式 */
body {
  font-family: Arial, sans-serif;
}

/* 表单样式 */
.el-form {
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-input {
  width: 300px;
  border-radius: 4px;
  transition: border-color 0.3s;
}

.el-input:focus {
  border-color: #409EFF; /* 聚焦时的边框颜色 */
}

/* 按钮样式 */
.el-button {
  border-radius: 4px;
}

.el-button:hover {
  background-color: #f0f0f0;
  border-color: #dcdcdc;
}

/* 表格样式 */
.el-table {
  border: 1px solid #dcdcdc;
  border-radius: 4px;
}

.el-table th,
.el-table td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #eaeaea;
}

.el-table th {
  background-color: #f9f9f9;
  font-weight: bold;
}

.el-table tr:nth-child(even) {
  background-color: #f7f7f7;
}

.el-table tr:hover {
  background-color: #ececec;
}

/* 无记录提示 */
p {
  text-align: center;
  color: #888;
  margin-top: 20px;
}

/* 自定义状态文本颜色 */
.status-paid {
  color: green;
}

.status-unpaid {
  color: red;
}

.status-pending {
  color: orange;
}
</style>